# -*- coding: UTF-8 -*-
from django import forms
from vdir.models import VDir
from django.shortcuts import get_object_or_404
import os

class RenameDirForm(forms.Form):
    newname = forms.CharField(max_length=64,
         widget=forms.TextInput(attrs={'class':'form-control',
             'placeholder':'输入文件夹名'}))  

    def __init__(self,data=None,instance=None, *args, **kwargs):
        super(RenameDirForm, self).__init__(data, *args, **kwargs)
        self.instance = instance

    def clean_newname(self):
        name = self.cleaned_data['newname']
        if not name:
            raise forms.ValidationError("文件名不能为空")


        dir = self.instance
        parent = dir.parent;
        if not parent:
            subdirs = VDir.objects.filter(parent=None)
        else: 
            subdirs = parent.vdir_set.all()

        if subdirs:
            samedir = subdirs.filter(name=name)

        if samedir and samedir.count()>0:
            print(22222222222)
            raise forms.ValidationError("不能创建相同的文件夹")


        return name

    def save(self):
        
        name = self.cleaned_data['newname']
        self.instance.name = name
        self.instance.save()

class CreateDirForm(forms.Form):
    parent =  forms.ModelChoiceField(queryset=VDir.objects.all(),widget=forms.Select(attrs={'class':'form-control'}),required=False)
    name = forms.CharField(max_length=64,
         widget=forms.TextInput(attrs={'class':'form-control',
             'placeholder':'输入文件夹名'}))


    def __init__(self,data=None,instance=None,pid=None, *args, **kwargs):
        super(CreateDirForm, self).__init__(data, *args, **kwargs)

        self.instance=instance
        if pid:
            self.fields['parent'].queryset = VDir.objects.filter(pk=pid)
            self.fields['parent'].empty_label = None
        else:
            self.fields['parent'].empty_label = '根目录'


    def clean_name(self):
        name = self.cleaned_data['name']
        try:
            parent = self.cleaned_data['parent']
            subdirs = parent.vdir_set.all()
        except:
            print('exception')
            subdirs = VDir.objects.filter(parent=None)

        if subdirs:
            samedir = subdirs.filter(name=name)

            if samedir.count()>0:
                raise forms.ValidationError("不能创建相同的文件夹")
        #dir = VDir.objects.get(pk=parent)
        # if dir==None:
        #     subdirs = VDir.objects.filter(parent=None)
        # else:
        #     subdirs = dir.vdir_set.all()

        # samedir = subdirs.objects.get(name=name)

        # if samedir!=None:
        #     raise forms.ValidationError("不能创建相同的文件夹")
        return name
    
    def save(self):
        name = self.cleaned_data['name']
        try:
            parent = self.cleaned_data['parent']
        except:
            parent = None

        if self.instance:
            pass

        else:
            try:
                from django.conf import settings

                if parent:
                    newpath = settings.MEDIA_ROOT+parent.get_full_path()+name
                    parent.add_ver()
                else:
                    newpath = settings.MEDIA_ROOT+name
                if not os.path.exists(newpath): os.makedirs(newpath)

                vdir = VDir()
                vdir.parent=parent
                vdir.name = name
                vdir.save()
            except Exception, e:
                raise e
            


        return vdir

